package com.jsoft.jsofted.sys.service.impl;

import com.jsoft.jsofted.sys.entity.OrgGroupEntity;
import com.jsoft.jsofted.sys.mapper.GroupMapper;
import com.jsoft.jsofted.framework.mybatis.CocQueryWrapper;
import com.jsoft.jsofted.framework.service.impl.CocServiceImpl;
import com.jsoft.jsofted.sys.service.GroupService;
import com.jsoft.jsofted.framework.utils.ObjectUtils;
import com.jsoft.jsofted.sys.vo.OrgGroupView;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Service
public class GroupServiceImpl extends CocServiceImpl<GroupMapper, OrgGroupEntity> implements GroupService {

    public List<OrgGroupView> queryGroupViewByUserId(String userId) {
        if (StringUtils.hasText(userId))
            return baseMapper.queryGroupViewByUserId("%" + userId + "%");

        return null;
    }

    protected CocQueryWrapper parseQueryWrapper(Map queryParams) {
        if (queryParams == null) {
            queryParams = new LinkedHashMap();
        }

        CocQueryWrapper queryWrapper = new CocQueryWrapper();
        this._parseOrgParams(queryWrapper, queryParams);
        this._parseUserParams(queryWrapper, queryParams);

        return queryWrapper;
    }

    /**
     * 解析【查询条件】中的【用户参数】
     */
    private void _parseUserParams(CocQueryWrapper queryWrapper, Map queryParams) {
        String userId = (String) queryParams.get("userId");
        if (StringUtils.hasText(userId)) {
            queryWrapper.like("members", userId);
        }
    }

    /**
     * 解析【查询条件】中的【机构参数】
     */
    private void _parseOrgParams(CocQueryWrapper queryWrapper, Map queryParams) {
        final String orgId = (String) queryParams.get("orgId");
        //
        final List<String> orgIdList = new ArrayList();
        List<String> _orgIdList = (List<String>) queryParams.get("orgIdList");
        if (_orgIdList != null && _orgIdList.size() > 0) {
            orgIdList.addAll(_orgIdList);
        }
        if (StringUtils.hasText(orgId) && !orgIdList.contains(orgId)) {
            orgIdList.add(orgId);
        }

        if (orgIdList.size() > 0) {
            Consumer<CocQueryWrapper> consumer = qw -> {
                String idListString = ObjectUtils.join(orgIdList, ",");
                if (orgIdList.size() > 0) {
                    qw.in("id", idListString);
                }
                if (StringUtils.hasText(orgId)) {
                    qw.or();
                    qw.subSelect("id", "REGEXP", "getOrgTreeIds({0})", orgId);
                }
            };
            queryWrapper.and(consumer);
        }
    }
}
